package com.boot.interceptor;

import com.boot.entity.Result;
import com.boot.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.boot.config.WebConfig.OPTIONS;

/**
 * @author bbyh
 * @since 2024-04-27
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    public static String tokenPrefix;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${token.prefix}")
    public void setTokenPrefix(String tokenPrefix) {
        TokenInterceptor.tokenPrefix = tokenPrefix;
    }

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        try {
            if (OPTIONS.equals(request.getMethod())) {
                return true;
            }

            String token = request.getHeader("token");
            String username = request.getHeader("username");
            if (token == null || username == null) {
                Result.writeResult(response, "token校验不通过");
                return false;
            }
            JwtUtil.verify(token, username);
            return token.equals(stringRedisTemplate.opsForValue().get(tokenPrefix + username));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            Result.writeResult(response, "token校验服务出错");
            return false;
        }
    }
}
